package com.dictionary.hi;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.custom.tab.AbstractViewController;
import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractTabActivity;
import com.inapp.util.BillingService;
import com.inapp.util.CPurchaseObserver;
import com.inapp.util.Consts;
import com.mango9x.utils.DatabaseAccessor;
import com.mango9x.utils.Utils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.ViewAnimator;

public class MainTabHostActivity extends AbstractTabActivity implements
		OnSharedPreferenceChangeListener {

	private static final String KEY_APP_START_COUNTER = "KEY_APP_START_COUNTER";
	public static final int[] RATING_PROMPT_INDEXES = { 1, 6, 12, 15, 20, 30,
			45, 66, 81, 99, 120, 150, 170, 200 };
	public static final String KEY_RATING_ENABLED = "KEY_RATING_ENABLED";

	private ImageLoader imageLoader;
	private SharedPreferences sharedPreferences;
	private ViewAnimator mainViewAnimator;
	private ViewAnimator tabContentConatiner;
	private View tabHeaderContainer;
	private LinearLayout tabHeaderPane;
	private View appTitleBar;
	private View purchaseView;
	private LinearLayout adContainer;

	private BillingService mBillingService;

	private List<View> tabHeaderList = new ArrayList<View>();
	private List<ViewAnimator> tabContents = new ArrayList<ViewAnimator>();
	private LayoutInflater layoutInflater;
	private SparseArray<AbstractTabRootManager> tabRootManagers = new SparseArray<AbstractTabRootManager>();
	private int currentSelectedTab = -1;
	private int displyWidth;
	private int displyHeight;
	private boolean isDeviceOnline;
	private boolean isProVersion;

	public boolean isProVersion() {
		return isProVersion;
	}

	private DatabaseAccessor databaseAccessor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.main);
			sharedPreferences = PreferenceManager
					.getDefaultSharedPreferences(this);
			sharedPreferences.registerOnSharedPreferenceChangeListener(this);

			isDeviceOnline = getIntent()
					.getBooleanExtra(Extra.IS_ONLINE, false);
			purchaseView = findViewById(R.id.imagePurchase);
			handlePurhcnaseButton();

			imageLoader = ImageLoader.getInstance();
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					getApplicationContext())
					.threadPoolSize(3)
					.threadPriority(Thread.NORM_PRIORITY - 2)
					.memoryCacheSize(1500000)
					// 1.5 Mb
					.denyCacheImageMultipleSizesInMemory()
					.discCacheFileNameGenerator(new Md5FileNameGenerator())
					.enableLogging() // Not necessary in common
					.build();
			imageLoader.init(config);
			DisplayMetrics metrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(metrics);
			displyWidth = metrics.widthPixels;
			displyHeight = metrics.heightPixels;

			mainViewAnimator = (ViewAnimator) findViewById(R.id.main_view_flipper);
			layoutInflater = LayoutInflater.from(this);
			appTitleBar = findViewById(R.id.app_title_bar);
			tabHeaderContainer = findViewById(R.id.horizontal_scroll_view);
			tabHeaderPane = (LinearLayout) findViewById(R.id.tab_header);
			tabContentConatiner = (ViewAnimator) findViewById(R.id.tab_content);
			adContainer = (LinearLayout) findViewById(R.id.linearLayout);
			mainViewAnimator.setDisplayedChild(1);
			final String[] TAB_TITLES = { getString(R.string.about),
					getString(R.string.upload), getString(R.string.favorites),
					getString(R.string.categories), getString(R.string.newest) };
			addTabs(TAB_TITLES);
			findViewById(R.id.imageView1).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							onMenuClick(v);
						}
					});
			findViewById(R.id.imageShare).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							shareApp();
						}
					});
			findViewById(R.id.imageRating).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							openMarket();
						}
					});

			purchaseView.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					// purchasePopup();
					requestPurchase(Extra.IN_APP_PRODUCT_ID);
				}
			});

			databaseAccessor = new DatabaseAccessor(this);
			databaseAccessor.open();
			boolean isOnline = Utils.isDeviceOnline(MainTabHostActivity.this);
			BillingService.register(new CPurchaseObserver(
					MainTabHostActivity.this));
			mBillingService = new BillingService();
			mBillingService.setContext(MainTabHostActivity.this);
			if (isOnline) {
				mBillingService.restoreInAppTransactions();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int getCurrentTab() {
		return currentSelectedTab;
	}

	public void setCurrentTab(int index) {
		if ((index >= 0) && (index < tabHeaderList.size())) {
			onTabTapped(tabHeaderList.get(index));
		}
	}

	public void hideTabWidget() {
		try {
			// tabHeaderPane.setVisibility(View.GONE);
			tabHeaderContainer.setVisibility(View.GONE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showTabWidget() {
		try {
			// tabHeaderPane.setVisibility(View.VISIBLE);
			tabHeaderContainer.setVisibility(View.VISIBLE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void hideTitleBar() {
		try {
			appTitleBar.setVisibility(View.GONE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showTitleBar() {
		try {
			appTitleBar.setVisibility(View.VISIBLE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public File getDatabasePath(String name) {
		return getApplication().getDatabasePath(name);
	}

	private void handlePurhcnaseButton() {
		try {
			isProVersion = BillingService.isPurchased(sharedPreferences,
					Extra.IN_APP_PRODUCT_ID)
					|| getPackageName().endsWith("pro");
			if (isProVersion) {
				purchaseView.setVisibility(View.GONE);
			} else {
				purchaseView.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void onTabTapped(View view) {
		try {
			for (int i = 0; i < tabHeaderList.size(); i++) {
				View v = tabHeaderList.get(i);
				if (view.equals(v)) {
					currentSelectedTab = i;
					v.setSelected(true);
					View child = tabContentConatiner.getChildAt(i);
					if ((child != null) && (child instanceof ViewAnimator)) {
						ViewAnimator vChild = (ViewAnimator) child;
						showTabContent(i, vChild);
					}
					tabContentConatiner.setDisplayedChild(i);
				} else {
					v.setSelected(false);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showTabContent(int index, ViewAnimator chaild) {
		try {

			AbstractTabRootManager tbManager = tabRootManagers.get(index);
			if (tbManager == null) {
				tbManager = new TabRootManager(this, layoutInflater, chaild,
						index);
				tabRootManagers.put(index, tbManager);
			}
			tbManager.onResume();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public View getView(String label) {
		View ret = null;
		try {
			final View tab = layoutInflater.inflate(R.layout.tab_indicator,
					null);
			// final ImageView iv = (ImageView)
			// tab.findViewById(R.id.tab_image);
			// iv.setImageResource(iconId);
			final TextView tv = (TextView) tab.findViewById(R.id.tab_label);
			tv.setText(label);
			tab.setClickable(true);
			tab.setFocusable(true);
			// iv.setFocusable(true);
			tv.setFocusable(true);
			tab.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					onTabTapped(v);

				}
			});
			ret = tab;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ret;
	}

	private void addTabs(String[] titles) {
		try {

			for (int i = 0; i < titles.length; i++) {
				View view = getView(titles[i]);
				// LinearLayout.LayoutParams lParam = new
				// LinearLayout.LayoutParams(
				// 0, LayoutParams.WRAP_CONTENT, 1.0F);
				LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				tabHeaderList.add(view);
				tabHeaderPane.addView(view, lParam);
				ViewAnimator viewAnimator = new ViewAnimator(this);
				android.view.ViewGroup.LayoutParams lParams2 = new android.view.ViewGroup.LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
				tabContents.add(viewAnimator);
				tabContentConatiner.addView(viewAnimator, lParams2);
			}
			tabHeaderPane.setWeightSum(1.0F * titles.length);
			if ((tabHeaderList.size() > 0)
					&& (tabHeaderList.size() == titles.length)) {
				if (isDeviceOnline) {
					onTabTapped(tabHeaderList.get(tabHeaderList.size() - 1));
				} else {
					onTabTapped(tabHeaderList.get(tabHeaderList.size() - 2));
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SharedPreferences getSharedPreferences() {
		return sharedPreferences;
	}

	@Override
	protected void onDestroy() {

		try {
			databaseAccessor.close();
			if (sharedPreferences != null) {
				sharedPreferences
						.unregisterOnSharedPreferenceChangeListener(this);
			}
			tabHeaderPane.removeAllViews();
			tabHeaderList.clear();
			tabContents.clear();
			for (int i = 0; i < tabRootManagers.size(); i++) {
				tabRootManagers.valueAt(i).onDestroy();
			}
			tabRootManagers.clear();

			if (mBillingService != null) {
				mBillingService.unbind();
				BillingService.unregister();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();

	}

	public void restartApp() {
		try {
			AbstractTabRootManager tabRootManager = tabRootManagers
					.get(currentSelectedTab);
			if (tabRootManager != null) {
				tabRootManager.onBackPressed();
			}
			int val = sharedPreferences.getInt(KEY_APP_START_COUNTER, 0) + 1;
			sharedPreferences.edit().putInt(KEY_APP_START_COUNTER, val)
					.commit();
			super.finish();
			Intent i = getBaseContext().getPackageManager()
					.getLaunchIntentForPackage(
							getBaseContext().getPackageName());
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onSharedPreferenceChanged(
			final SharedPreferences sharedPreferences, final String key) {
		runOnUiThread(new Runnable() {

			public void run() {
				try {
					if (BillingService.KEY_IN_APP_PURCHASED_ITEM_CHANGED_TIME
							.equals(key)) {
						restartApp();
					}

					for (int i = 0; i < tabRootManagers.size(); i++) {
						tabRootManagers.valueAt(i).onSharedPreferenceChanged(
								sharedPreferences, key);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		});
	}

	public void sendBroadcastMessage(String key, String message) {
		try {
			for (int i = 0; i < tabRootManagers.size(); i++) {
				tabRootManagers.valueAt(i).broadcastMessageReceived(key,
						message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private SparseArray<AbstractViewController> avcs = new SparseArray<AbstractViewController>();

	public void startActivityForResult(Intent intent, int requestCode,
			AbstractViewController avc) {
		avcs.put(requestCode, avc);
		super.startActivityForResult(intent, requestCode);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			AbstractViewController avc = avcs.get(requestCode);
			if (avc != null) {
				avc.onActivityResult(requestCode, resultCode, data);
			} else {
				super.onActivityResult(requestCode, resultCode, data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void finish() {
		try {
			AbstractTabRootManager tabRootManager = tabRootManagers
					.get(getCurrentTab());
			if (tabRootManager != null) {
				// boolean ret = tabRootManager.onBackPressed();
				// if (!ret) {
				// showExitConfirmation();
				// }
				int childCount = tabRootManager.getChildCount();

				if (childCount <= 1) {
					showExitConfirmation();
				} else {
					tabRootManager.onBackPressed();
				}
			} else {
				showExitConfirmation();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showExitConfirmation() {
		try {
			new AlertDialog.Builder(this)
					.setMessage("هل تريد إغلاق صور منوعة ؟")
					.setCancelable(false)
					.setPositiveButton("نعم",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									finishConfirmed();
								}
							}).setNegativeButton("لا", null).show();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void purchasePopup() {
		try {
			new AlertDialog.Builder(this)
					.setMessage("شراء النسخة الكاملة ؟")
					.setCancelable(false)
					.setPositiveButton("نعم",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									requestPurchase(Extra.IN_APP_PRODUCT_ID);
								}
							}).setNegativeButton("لا", null).show();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void finishConfirmed() {
		try {
			AbstractTabRootManager tabRootManager = tabRootManagers
					.get(currentSelectedTab);
			if (tabRootManager != null) {
				tabRootManager.onBackPressed();
			}

			int val = sharedPreferences.getInt(KEY_APP_START_COUNTER, 0) + 1;
			sharedPreferences.edit().putInt(KEY_APP_START_COUNTER, val)
					.commit();
			boolean isRatingEnabled = sharedPreferences.getBoolean(
					KEY_RATING_ENABLED, true);
			boolean showRatingOption = false;
			if (isRatingEnabled) {
				for (int i = 0; i < RATING_PROMPT_INDEXES.length; i++) {
					if (RATING_PROMPT_INDEXES[i] == val) {
						showRatingOption = true;
						break;

					}
				}
			}
			if (showRatingOption) {
				showRatingOptions();
			} else {
				exit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showRatingOptions() {
		try {
			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("هل أعجبك التطبيق ؟ شاركنا تقييمك")
					.setCancelable(false)
					.setPositiveButton("نعم",
							new DialogInterface.OnClickListener() {
								public void onClick(
										final DialogInterface dialog,
										final int id) {

									rateTheApp();

								}
							})
					.setNegativeButton("لا",
							new DialogInterface.OnClickListener() {
								public void onClick(
										final DialogInterface dialog,
										final int id) {
									exit();
								}
							});
			final AlertDialog alert = builder.create();
			alert.setTitle("تقييم التطبيق");
			alert.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void exit() {
		super.finish();
	}

	private void rateTheApp() {
		try {
			sharedPreferences.edit().putBoolean(KEY_RATING_ENABLED, false)
					.commit();
			openMarket();
			exit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void openMarket() {
		try {
			String packageName = getPackageName();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://details?id=" + packageName));
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void shareApp() {
		try {
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");

			intent.putExtra(Intent.EXTRA_SUBJECT, "مشاركة التطبيق");
			intent.putExtra(Intent.EXTRA_TEXT,
					"http://market.android.com/details?id=com.mango9x.newimages");

			Intent chooser = Intent.createChooser(intent, "مشاركة بواسطة :");
			startActivity(chooser);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showMoreApps() {
		try {
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setData(Uri.parse(getString(R.string.more_apps_url)));
			startActivity(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showAbout() {
		try {
			new AlertDialog.Builder(this)
					.setMessage(getString(R.string.about_text))
					.setCancelable(false)
					.setTitle("عن التطبيق")
					.setPositiveButton("إغلاق",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							}).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void requestPurchase(String itemId) {
		try {
			if (mBillingService.requestPurchase(itemId, Consts.ITEM_TYPE_INAPP,
					null)) {
				Toast.makeText(this, "سيتم إبلاغك عند إكتمال الشراء",
						Toast.LENGTH_LONG).show();

			} else {
				Toast.makeText(this, "الشراء غير مدعوم", Toast.LENGTH_LONG)
						.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onMenuClick(View v) {
		String[] itemNames = { "Menu", "Menu" };
		// AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog.Builder builder = new AlertDialog.Builder(
				MainTabHostActivity.this);

		builder.setTitle("Menu");
		builder.setItems(itemNames, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				if (item == 2) {
					showMoreApps();

				} else if (item == 3) {
					showAbout();
				}
				dialog.cancel();
			}

		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public ImageLoader getImageLoader() {
		return imageLoader;
	}

	public int getDisplyWidth() {
		return displyWidth;
	}

	public int getDisplyHeight() {
		return displyHeight;
	}

	public DatabaseAccessor getDatabaseAccessor() {
		return databaseAccessor;
	}
}
